/**
 * Created by Jimmy on 16/9/23.
 */
//棋盘
var board = new Array();
//分数
var score = 0;
//碰撞检测,发生过碰撞的不在进行碰撞,比如 2 2 4 8 --> 4 4 8 0 而不是变成 16 0 0 0
var hasCollide = new Array();

//触摸的起始,结束坐标
var touchstartX;
var touchstartY;
var touchendX;
var touchendY;

$(function () {
    fitMobile();
    newgame();
});

//适配手机屏幕
function fitMobile() {
    //网页的处理
    if (boardSize > 500) {
        boardSize = 500;
        boardSpace = 20;
        boardCell = 100;
    }
    $("#header-container").css("width", boardSize);

    $(".score-container").css("width", boardCell);
    $(".best-container").css("width", boardCell);

    $("#grid-container").css("width", boardSize - 2 * boardSpace);
    $("#grid-container").css("height", boardSize - 2 * boardSpace);
    $("#grid-container").css("padding", boardSpace);
    $("#grid-container").css("border-radius", 0.02 * boardSize);

    $(".grid-cell").css("width", boardCell);
    $(".grid-cell").css("height", boardCell);
    $(".grid-cell").css("border-radius", 0.06 * boardCell);

    $("#end-container").css("width", boardSize);
    $("#gameover").css("marginTop", boardSize / 3);
}

function newgame() {
    //初始化棋盘
    initboard();
    //棋盘格随机产生2个数字
    setTimeout("genrateOneNumber()", 100);
    setTimeout("genrateOneNumber()", 100);
}

function initboard() {
    $("#end-container").hide();
    $("#grid-container").css("opacity", 1.0);
    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            var gridcell = $("#grid-cell-" + i + "-" + j);
            //设置css属性(每个grid的top和left)
            gridcell.css("top", getTopPos(i, j));
            gridcell.css("left", getLeftPos(i, j));
        }
    }
    //初始化二维数组
    for (var i = 0; i < 4; i++) {
        board[i] = new Array();
        hasCollide[i] = new Array();
        for (var j = 0; j < 4; j++) {
            board[i][j] = 0;
            hasCollide[i][j] = false;
        }
    }
    score = 0;
    updateScore(score); //分数
    updateBestScore(getBestScore()); //最高分
    setTimeout("updateBoardView()", 100);
}

//更新UI
function updateBoardView() {
    $(".number-cell").remove();
    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            //添加number-cell元素
            $("#grid-container").append('<div class="number-cell" id="number-cell-' + i + '-' + j + '"></div>');
            var thisNumbercell = $("#number-cell-" + i + "-" + j);
            if (board[i][j] == 0) { //不需要显示
                thisNumbercell.css("width", "0px");
                thisNumbercell.css("height", "0px");
                thisNumbercell.css("top", getTopPos(i, j) + boardCell / 2);
                thisNumbercell.css("left", getLeftPos(i, j) + boardCell / 2);
            } else { //绘制
                thisNumbercell.css("width", boardCell);
                thisNumbercell.css("height", boardCell);
                thisNumbercell.css("top", getTopPos(i, j));
                thisNumbercell.css("left", getLeftPos(i, j));
                //绘制背景色
                thisNumbercell.css("background-color", getNumberBackgroundColor(board[i][j]));
                //绘制文字颜色
                thisNumbercell.css("color", getNumberTextColor(board[i][j]));
                //绘制文字
                thisNumbercell.text(board[i][j]);
            }
            //初始化
            hasCollide[i][j] = false;
        }
    }
    $(".number-cell").css("border-radius", 0.06 * boardCell);
    $(".number-cell").css("line-height", boardCell + "px");
    $(".number-cell").css("font-size", 0.6 * boardCell + "px");
}

//UI随机位置生成2或4
function genrateOneNumber() {
    if (noSpace(board))
        return false;

    var arr = new Array();
    //动态生成位置
    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            if (board[i][j] == 0) {
                arr.push(4 * i + j);
            }
        }
    }
    var index = parseInt(Math.floor(Math.random() * arr.length));//0-arr.length的随机数
    var value = arr[index];
    var randomX = parseInt(value / 4);
    var randomY = value % 4;
    //动态生成数字
    var num = Math.random() < 0.5 ? 2 : 4; //2和4的概率一半
    //绘制动态数字(加入动画)
    board[randomX][randomY] = num;
    showNumberAnim(randomX, randomY, num);
    return true;
}

//开始触摸
document.addEventListener("touchstart", function (event) {
    touchstartX = event.touches[0].pageX;
    touchstartY = event.touches[0].pageY;
});

//移动
document.addEventListener("touchmove", function (event) {
    //阻止默认滚动条
    event.preventDefault();
});

//结束触摸
document.addEventListener("touchend", function (event) {
    touchendX = event.changedTouches[0].pageX;
    touchendY = event.changedTouches[0].pageY;

    var deltaX = touchendX - touchstartX;
    var deltaY = touchendY - touchstartY;

    //设定移动识别距离
    if (Math.abs(deltaX) < 30 && Math.abs(deltaY) < 30)
        return;

    if (Math.abs(deltaX) >= Math.abs(deltaY)) {
        if (deltaX < 0) { //向左移动
            if (moveLeft()) {
                setTimeout("updateBoardView()", 200);
                setTimeout("genrateOneNumber()", 210);
                setTimeout("isgameOver()", 300);
            }
        } else { //向右移动
            if (moveRight()) {
                setTimeout("updateBoardView()", 200);
                setTimeout("genrateOneNumber()", 210);
                setTimeout("isgameOver()", 300);
            }
        }
    } else {
        if (deltaY < 0) { //向上移动
            if (moveUp()) {
                setTimeout("updateBoardView()", 200);
                setTimeout("genrateOneNumber()", 210);
                setTimeout("isgameOver()", 300);
            }
        } else { //向下移动
            if (moveDown()) {
                setTimeout("updateBoardView()", 200);
                setTimeout("genrateOneNumber()", 210);
                setTimeout("isgameOver()", 300);
            }
        }
    }


});


//按键方法
$(document).keydown(function (event) {
    switch (event.keyCode) {
        case 37: //left
            event.preventDefault();
            if (moveLeft()) {
                setTimeout("updateBoardView()", 200);
                setTimeout("genrateOneNumber()", 210);
                setTimeout("isgameOver()", 300);
            }
            break;
        case 38: //up
            event.preventDefault();
            if (moveUp()) {
                setTimeout("updateBoardView()", 200);
                setTimeout("genrateOneNumber()", 210);
                setTimeout("isgameOver()", 300);
            }
            break;
        case 39: //right
            event.preventDefault();
            if (moveRight()) {
                setTimeout("updateBoardView()", 200);
                setTimeout("genrateOneNumber()", 210);
                setTimeout("isgameOver()", 300);
            }
            break;
        case 40: //down
            event.preventDefault();
            if (moveDown()) {
                setTimeout("updateBoardView()", 200);
                setTimeout("genrateOneNumber()", 210);
                setTimeout("isgameOver()", 300);
            }
            break;
        default:

            break;
    }
});

//向左移动
function moveLeft() {
    if (!canMoveLeft(board)) //不能向左移动
        return false;
    //向左移动
    for (var i = 0; i < 4; i++) {
        for (var j = 1; j < 4; j++) {//不用判断第一列的情况
            if (board[i][j] != 0) {
                for (var k = 0; k < j; k++) { //和当前数字的左边的数字进行比较
                    //条件1:左边的数字是0,并且中间没有其他数字阻碍
                    //条件2:左边的数字和当前的数字一样大,并且中间没有其他数字阻碍
                    if (board[i][k] == 0 && noBlockHorizontal(i, k, j, board)) {
                        //动画移动
                        showNumberMoveAnim(i, j, i, k);
                        //数据操作
                        board[i][k] = board[i][j];
                        board[i][j] = 0;
                        break;
                    } else if (board[i][k] == board[i][j] && noBlockHorizontal(i, k, j, board) && !hasCollide[i][k]) {
                        //动画移动
                        showNumberMoveAnim(i, j, i, k);
                        //数字相加
                        board[i][k] += board[i][j];
                        board[i][j] = 0;
                        //刷新分数
                        score += board[i][k];
                        updateScore(score);
                        saveBestScore();
                        updateBestScore(getBestScore());
                        //发生碰撞,进行记录
                        hasCollide[i][k] = true;
                        break;
                    }
                }
            }
        }
    }
    return true;
}

//向上移动
function moveUp() {
    if (!canMoveUp(board))
        return false;
    //向上移动
    for (var i = 1; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            if (board[i][j] != 0) {
                for (var k = 0; k < i; k++) {
                    //条件1:上方的数字是0,并且中间没有其他数字阻碍
                    //条件2:上方的数字和当前的数字一样大,并且中间没有其他数字阻碍
                    if (board[k][j] == 0 && noBlockVertical(j, k, i, board)) {
                        //动画移动
                        showNumberMoveAnim(i, j, k, j);
                        //数据操作
                        board[k][j] = board[i][j];
                        board[i][j] = 0;
                        break;
                    } else if (board[k][j] == board[i][j] && noBlockVertical(j, k, i, board) && !hasCollide[k][j]) {
                        //动画移动
                        showNumberMoveAnim(i, j, k, j);
                        //数字相加
                        board[k][j] += board[i][j];
                        board[i][j] = 0;
                        //刷新分数
                        score += board[k][j];
                        updateScore(score);
                        saveBestScore();
                        updateBestScore(getBestScore());
                        //发生碰撞,进行记录
                        hasCollide[k][j] = true;
                        break;
                    }
                }
            }
        }
    }
    return true;
}

//向右移动
function moveRight() {
    if (!canMoveRight(board))
        return false;
    //向右移动
    for (var i = 0; i < 4; i++) {
        for (var j = 2; j >= 0; j--) {//不用判断最后一列的情况
            if (board[i][j] != 0) {
                for (var k = 3; k > j; k--) { //和当前数字的右边的数字进行比较
                    //条件1:右边的数字是0,并且中间没有其他数字阻碍
                    //条件2:右边的数字和当前的数字一样大,并且中间没有其他数字阻碍
                    if (board[i][k] == 0 && noBlockHorizontal(i, j, k, board)) {
                        //动画移动
                        showNumberMoveAnim(i, j, i, k);
                        //数据操作
                        board[i][k] = board[i][j];
                        board[i][j] = 0;
                        break;
                    } else if (board[i][k] == board[i][j] && noBlockHorizontal(i, j, k, board) && !hasCollide[i][k]) {
                        //动画移动
                        showNumberMoveAnim(i, j, i, k);
                        //数字相加
                        board[i][k] += board[i][j];
                        board[i][j] = 0;
                        //刷新分数
                        score += board[i][k];
                        updateScore(score);
                        saveBestScore();
                        updateBestScore(getBestScore());
                        //发生碰撞,进行记录
                        hasCollide[i][k] = true;
                        break;
                    }
                }
            }
        }
    }
    return true;
}


//向下移动
function moveDown() {
    if (!canMoveDown(board))
        return false;
    //向下移动
    for (var i = 2; i >= 0; i--) {
        for (var j = 0; j < 4; j++) {
            if (board[i][j] != 0) {
                for (var k = 3; k > i; k--) {
                    //条件1:下方的数字是0,并且中间没有其他数字阻碍
                    //条件2:下方的数字和当前的数字一样大,并且中间没有其他数字阻碍
                    if (board[k][j] == 0 && noBlockVertical(j, i, k, board)) {
                        //动画移动
                        showNumberMoveAnim(i, j, k, j);
                        //数据操作
                        board[k][j] = board[i][j];
                        board[i][j] = 0;
                        break;
                    } else if (board[k][j] == board[i][j] && noBlockVertical(j, i, k, board) && !hasCollide[k][j]) {
                        //动画移动
                        showNumberMoveAnim(i, j, k, j);
                        //数字相加
                        board[k][j] += board[i][j];
                        board[i][j] = 0;
                        //刷新分数
                        score += board[k][j];
                        updateScore(score);
                        saveBestScore();
                        updateBestScore(getBestScore());
                        //发生碰撞,进行记录
                        hasCollide[k][j] = true;
                        break;
                    }
                }
            }
        }
    }
    return true;
}

//游戏结束
function isgameOver() {
    if (noSpace(board) && noMove(board))
        gameOver();
}

function gameOver() {
    //显示游戏结束
    $("#grid-container").css("opacity", 0.4);
    $("#end-container").show();
}


//存储最高分
function saveBestScore() {
    if (typeof(Storage) !== "undefined") {
        if (score > getBestScore()) {
            localStorage.highScore = score;
        }
    }
}

//获取最高分
function getBestScore() {
    if (typeof(Storage) !== "undefined" && typeof(localStorage.highScore) !== "undefined") {
        return localStorage.highScore;
    }
    return 0;
}